package com.block.datapush.service.filter;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.block.datapush.model.param.FilterHandlerParam;
import com.block.datapush.model.result.FilterHandlerResult;
import com.block.datapush.service.IDataFilterItemService;
import com.block.db.entity.MemberSourceInfo;
import org.springframework.stereotype.Service;

import java.sql.Struct;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class FilterOrFilterHandlerService implements IDataFilterItemService {

    @Override
    public FilterHandlerResult handlerFilterLogic(FilterHandlerParam handlerParam, MemberSourceInfo memberSourceInfo) {

        String filterValue = handlerParam.getOrFilter();
        if (StrUtil.isEmpty(filterValue)){
            return FilterHandlerResult.success();
        }

        List<String> valueList = JSON.parseArray(filterValue, String.class);
        if (CollUtil.isEmpty(valueList)){
            return FilterHandlerResult.success();
        }

        // 用户的条件
        List<String> userValueList = new ArrayList<>();
        userValueList.add(this.getCommonOrFilter(memberSourceInfo.getHouse()));
        userValueList.add(this.getCommonOrFilter(memberSourceInfo.getCar()));
        userValueList.add(this.getCommonOrFilter(memberSourceInfo.getGjj()));
        userValueList.add(this.getCommonOrFilter(memberSourceInfo.getShebao()));
        userValueList.add(this.getCommonOrFilter(memberSourceInfo.getBaoxian()));
        userValueList.add(this.getCommonOrFilter(memberSourceInfo.getHuabei()));
        userValueList.add(this.getCommonOrFilter(memberSourceInfo.getBaitiao()));
        userValueList.add(this.getYuQiOrFilter(memberSourceInfo.getYuqi()));

        // 获取资质的交集
        Collection<String> resultList = CollUtil.intersection(userValueList, valueList);
        if (CollUtil.isNotEmpty(resultList)){
            // 任选一不为空，满足条件，
            return FilterHandlerResult.success();
        }

        String message = StrUtil.format("【resultList】{}【valueList】{}【userValueList】{}",
                JSON.toJSONString(resultList), JSON.toJSONString(valueList), JSON.toJSONString(userValueList));
        return FilterHandlerResult.error("ORFILTER_ERROR", message);
    }

    public String getCommonOrFilter(String sourceValue){
        if (StrUtil.isEmpty(sourceValue)){
            return "";
        }
        if (!sourceValue.contains("001")){
            String key = StrUtil.subPre(sourceValue, sourceValue.length() - 3);
            return key + "000";
        }
        return sourceValue;
    }

    public String getYuQiOrFilter(String sourceValue){
        if (StrUtil.isEmpty(sourceValue)){
            return "";
        }
        if (StrUtil.equals(sourceValue, "yq001")){
            return "yq000";
        }
        return sourceValue;
    }

}
